import Vue from "vue";
import VueRouter from "vue-router";
Vue.use(VueRouter);

import routes from "./routes"
import store from "@/store"
// 解决 Vue Router 在重复导航到同一路由时抛出的警告
// 重写push/replace方法
let originPush = VueRouter.prototype.push;
let originReplace = VueRouter.prototype.replace;
VueRouter.prototype.push = function (location, resolve, reject) {
  if (resolve && reject) {
    // 如果用户手动提供了成功和失败回调，直接调用原始方法
    originPush.call(this, location, resolve, reject);
  } else {
    originPush.call(this, location).catch((err) => err);
  }
};
VueRouter.prototype.replace = function (location, resolve, reject) {
  if (resolve && reject) {
    originReplace.call(this, location, resolve, reject);
  } else {
    originReplace.call(this, location).catch((err) => err);
  }
};


// 路由配置
let router = new VueRouter({
  routes,
  scrollBehavior(to, from, savePosition) {
    return { y: 0 }
  }
})

// 全局前置守卫
router.beforeEach(async (to, from, next) => {
  // to到哪去，from从哪来， next放行函数。next() / next(path) / next(false)
  next()
  let token = store.state.user.token
  let name = store.state.user.userinfo.name
  // 用户已登录
  if(token) {
    // 禁止访问登陆注册页
    if (to.path == '/login' || to.path == "/register") {
      next('/home')
    }else {
      //已经登陆了,访问的是非登录与注册
      //登录了且拥有用户信息放行
      if (name) {
        next();
      } else {
        //登陆了且没有用户信息
        //在路由跳转之前获取用户信息且放行
        try {
          //获取用户信息
          await store.dispatch("getUserInfo");
          next();
        } catch (error) {
          //token失效重新登录
          //清除token
          await store.dispatch("logout");
          // 回到登录页
          this.$router.push("/login");
        }
      }
    }
  }else{
    // 用户未登录
    //禁止访问交易（trade）、支付(pay|paysuccess)、个人中心(center/myorder|center/grouporder)路由
    if (to.path == '/trade' || to.path == '/pay' || to.path == '/paysuccess' || to.path == '/center/myorder' || to.path == 'center/grouporder' ||to.path == '/center') {
      //把未登录的时候向去而没有去成的信息，存储于地址栏中【路由】
      alert("请先登录")
      next('/login?redirect=' + to.path)
    }
    // 访问其他路由放行
    else {
      next()
    }
  }
})



export default router